﻿using Newtonsoft.Json;
using System.Data;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Serialization;

namespace Util
{
    /// <summary>
    /// 本类用于放置本地网络请求参数
    /// </summary>
    public class NetApiUtil
    {
        private readonly HttpClient _httpClient;

        public NetApiUtil()
        {
            _httpClient = new HttpClient();
        }
        /// <summary>
        /// API的GET请求，用于请求关于GET的API方法
        /// </summary>
        /// <param name="url">连接地址</param>
        /// <param name="param">自定义参数</param>
        /// /// <param name="result">接受的参数值</param>
        /// <returns></returns>
        public async Task<T> ApiGet<T>(string url, Dictionary<string, string> param, T result)
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置API的URL
                StringBuilder apiUrl = new StringBuilder(url);
                //因为参数是动态的，所以用stringbuilder
                StringBuilder urlparam = new StringBuilder(); 
                if (param.Count > 0)
                {
                    urlparam.Append("?");
                    int i = 0;
                    foreach (var item in param)
                    {
                        if (i > 0)
                            urlparam.Append("&");
                        urlparam.AppendFormat("{0}={1}", item.Key, item.Value);
                        i++;
                    }
                }
                apiUrl.Append(urlparam.ToString());
                // 为了方便自定义参数，所以设计思路
                //var parameters = JsonConvert.DeserializeObject(param);

                // 发起POST请求，并将参数序列化为JSON格式
                HttpResponseMessage response = await client.GetAsync(apiUrl.ToString());

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    ///将结果序列化转为json格式
                    //var parameters = JsonConvert.DeserializeObject(responseBody);
                    //JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                    T list = JsonConvert.DeserializeObject<T>(responseBody);    //将json数据转化为对象类型并赋值给list

                    //序列化：转换Json格式
                    result = list;


                    //Console.WriteLine("Response: " + parameters);
                }
                else
                {
                    Console.WriteLine("API request failed with status code: " + response.StatusCode);
                }
            }

            return result;
        }

        /// <summary>
        /// API的GET请求，用于请求关于GET的API方法
        /// </summary>
        /// <param name="url">连接地址</param>
        /// <param name="param">自定义参数</param>
        /// /// <param name="result">接受的参数值</param>
        /// <returns></returns>
        public async Task<T> ApiPOST<T>(string url,string param, T result)
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置API的URL
                string apiUrl = url;

                // 为了方便自定义参数，所以设计思路
                var parameters = JsonConvert.DeserializeObject(param);

                // 发起POST请求，并将参数序列化为JSON格式
                HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl,parameters);

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Response: " + responseBody);
                }
                else
                {
                    Console.WriteLine("API request failed with status code: " + response.StatusCode);
                }
            }

            return result;
        }
    }
}